package im.agents.service;

import im.domain.SLA;
import im.domain.XMLSerializer;
import jade.core.AID;
import jade.core.Agent;
import jade.domain.FIPANames.InteractionProtocol;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.proto.ContractNetResponder;

/**
 * Risponde alla proposta di stipulare un SLA in base a parametri specificati 
 * dall'agente subscriber. Implementa il protocollo <tt>FIPA CONTRACT NET</tt>.
 *  
 * @author Savino
 * @see im.agents.slachecker.NegotiateSLAInitiator
 */
public class NegotiateSLAResponder extends ContractNetResponder {

	public NegotiateSLAResponder(Agent a, MessageTemplate mt) {
		super(a, mt);
		// TODO Auto-generated constructor stub
	}

	/**
	 * Risponde alla <tt>CALL FOR PROPOSALS</tt> con la propria proposta 
	 * per l'agreement sul servizio richiesto.
	 */
	protected ACLMessage handleCfp(ACLMessage cfp){
		ACLMessage proposal = cfp.createReply();
		proposal.setPerformative(ACLMessage.PROPOSE);
		proposal.setProtocol(InteractionProtocol.FIPA_CONTRACT_NET);
		SLA requested = (SLA)XMLSerializer.doDeserialize(cfp.getContent());
		
		if(requested!=null && requested.getServizio()!=null){
			SLA proSLA= getMyAgent().getSLAProposal(requested.getServizio());
			proSLA.setSubscriberA(requested.getSubscriberA());
			proSLA.setSubscriberB(getMyAgent().getAID());
			proposal.setContent(XMLSerializer.doSerialize(proSLA));
		}else{
			proposal.setPerformative(ACLMessage.REFUSE);
		}
		//System.out.println("Received CFP from "+cfp.getSender().getLocalName());
		return proposal;		
	}
	
	/**
	 * Risponde al messaggio di <tt>ACCEPT-PROPOSAL</tt> con <tt>INFORM</tt>
	 */
	protected ACLMessage handleAcceptProposal(ACLMessage cfp, 
			ACLMessage propose, ACLMessage accept){
		AID slaChecker = accept.getSender();
		ACLMessage re = accept.createReply();
		re.setPerformative(ACLMessage.INFORM);
		//System.out.println(propose.getSender().getLocalName()+" ACCEPTED proposal");
		SLA sla = (SLA) XMLSerializer.doDeserialize(cfp.getContent());
		sla.setSubscriberB(myAgent.getAID());
		getMyAgent().getSubscribedSLAs().put(sla.toString(), sla);
		getMyAgent().getSlaCheckers().put(sla.toString(), slaChecker);
		myAgent.addBehaviour(new HandleViolations(
				myAgent,sla));
		return re;
	}
	
	
	protected void handleOutOfSequence(ACLMessage out){
		System.out.println("from "+out.getSender().getLocalName()+
				" -  outofseq");
		
	}
	protected ServiceProvider getMyAgent(){
		return (ServiceProvider)myAgent;
	}
	

}

